//
//  ViewController.m
//  KooIEDUCalendarDemo
//
//  Created by nowcoder on 2025/6/18.
//

#import "ViewController.h"
#import "KooCalendarView.h"
#import "KooCalendarConfig.h"
#import <Masonry/Masonry.h>

@interface ViewController () <KooCalendarViewDelegate, KooCalendarDataSource>

// UI Components
@property (nonatomic, strong) KooCalendarView *calendarView;
@property (nonatomic, strong) UILabel *selectedDatesLabel;
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, strong) UIButton *clearButton;
@property (nonatomic, strong) UIButton *removeLastButton;
@property (nonatomic, strong) UIButton *themeButton;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;

// Data
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, assign) NSInteger currentThemeIndex;

@end

@implementation ViewController

#pragma mark - Lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupDateFormatter];
    [self setupUI];
    [self setupConstraints];
    [self setupInitialData];
}

#pragma mark - Setup Methods

- (void)setupDateFormatter {
    self.dateFormatter = [[NSDateFormatter alloc] init];
    self.dateFormatter.dateFormat = @"yyyy-MM-dd";
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor systemBackgroundColor];
    self.title = @"日历组件演示";
    self.currentThemeIndex = 0;
    
    // 创建滚动视图
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.backgroundColor = [UIColor clearColor];
    self.scrollView.showsVerticalScrollIndicator = YES;
    self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
    [self.view addSubview:self.scrollView];
    
    // 创建内容视图
    self.contentView = [[UIView alloc] init];
    self.contentView.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:self.contentView];
    
    // 创建日历组件
    [self setupCalendarView];
    
    // 创建状态标签
    self.statusLabel = [[UILabel alloc] init];
    self.statusLabel.text = @"📅 请选择日期（最多10个）";
    self.statusLabel.font = [UIFont systemFontOfSize:15];
    self.statusLabel.textColor = [UIColor labelColor];
    self.statusLabel.textAlignment = NSTextAlignmentCenter;
    self.statusLabel.numberOfLines = 0;
    [self.contentView addSubview:self.statusLabel];
    
    // 创建选中日期标签
    self.selectedDatesLabel = [[UILabel alloc] init];
    self.selectedDatesLabel.text = @"当前选中的日期：无";
    self.selectedDatesLabel.font = [UIFont systemFontOfSize:13];
    self.selectedDatesLabel.textColor = [UIColor secondaryLabelColor];
    self.selectedDatesLabel.textAlignment = NSTextAlignmentLeft;
    self.selectedDatesLabel.numberOfLines = 0;
    [self.contentView addSubview:self.selectedDatesLabel];
    
    // 创建清空按钮
    self.clearButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.clearButton setTitle:@"清空选择" forState:UIControlStateNormal];
    self.clearButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.clearButton setTitleColor:[UIColor systemRedColor] forState:UIControlStateNormal];
    self.clearButton.layer.borderWidth = 1;
    self.clearButton.layer.borderColor = [UIColor systemRedColor].CGColor;
    self.clearButton.layer.cornerRadius = 8;
    [self.clearButton addTarget:self action:@selector(clearButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.clearButton];
    
    // 创建删除最后一个日期按钮
    self.removeLastButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.removeLastButton setTitle:@"删除最后" forState:UIControlStateNormal];
    self.removeLastButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.removeLastButton setTitleColor:[UIColor systemOrangeColor] forState:UIControlStateNormal];
    self.removeLastButton.layer.borderWidth = 1;
    self.removeLastButton.layer.borderColor = [UIColor systemOrangeColor].CGColor;
    self.removeLastButton.layer.cornerRadius = 8;
    [self.removeLastButton addTarget:self action:@selector(removeLastButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.removeLastButton];
    
    // 创建主题切换按钮
    self.themeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.themeButton setTitle:@"切换主题" forState:UIControlStateNormal];
    self.themeButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.themeButton setTitleColor:[UIColor systemBlueColor] forState:UIControlStateNormal];
    self.themeButton.layer.borderWidth = 1;
    self.themeButton.layer.borderColor = [UIColor systemBlueColor].CGColor;
    self.themeButton.layer.cornerRadius = 8;
    [self.themeButton addTarget:self action:@selector(themeButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.themeButton];
}

- (void)setupCalendarView {
    // 创建预设选中日期（明天和后天）
    NSDate *tomorrow = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay 
                                                               value:1 
                                                              toDate:[NSDate date] 
                                                             options:0];
    NSDate *dayAfterTomorrow = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay 
                                                                       value:2 
                                                                      toDate:[NSDate date] 
                                                                     options:0];
    NSArray *preSelectedDates = @[tomorrow, dayAfterTomorrow];
    
    // 使用图片设计配置和预设日期创建日历
    self.calendarView = [[KooCalendarView alloc] initWithConfig:[KooCalendarConfig imageBasedConfig] 
                                                preSelectedDates:preSelectedDates];
    self.calendarView.delegate = self;
    self.calendarView.dataSource = self;
    self.calendarView.backgroundColor = [UIColor systemBackgroundColor];
    self.calendarView.layer.cornerRadius = 12;
    self.calendarView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.calendarView.layer.shadowOffset = CGSizeMake(0, 2);
    self.calendarView.layer.shadowOpacity = 0.1;
    self.calendarView.layer.shadowRadius = 4;
    [self.contentView addSubview:self.calendarView];
}

- (void)setupConstraints {
    // 滚动视图约束
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.edges.equalTo(self.view);
        } else {
            make.top.equalTo(self.mas_topLayoutGuide);
            make.left.right.bottom.equalTo(self.view);
        }
    }];
    
    // 内容视图约束
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
        // 确保内容视图有最小高度
        make.height.greaterThanOrEqualTo(self.scrollView);
    }];
    
    // 状态标签约束 - 减少顶部间距
    [self.statusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(10);
        make.left.right.equalTo(self.contentView).inset(16);
        make.height.equalTo(@230);
    }];
    
    // 日历视图约束 - 减少间距，调整高度
    [self.calendarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.statusLabel.mas_bottom).offset(10);
        make.left.right.equalTo(self.contentView).inset(16);
        make.height.greaterThanOrEqualTo(@380);
    }];
    
    // 选中日期标签约束 - 减少间距
    [self.selectedDatesLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        //make.top.equalTo(self.calendarView.mas_bottom).offset(10);
        make.left.right.equalTo(self.contentView).inset(16);
        make.height.greaterThanOrEqualTo(@50);
    }];
    
    // 按钮约束 - 三个按钮横向排列
    [self.clearButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.selectedDatesLabel.mas_bottom).offset(15);
        make.left.equalTo(self.contentView).offset(16);
        make.width.equalTo(@80);
        make.height.equalTo(@36);
    }];
    
    [self.removeLastButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.selectedDatesLabel.mas_bottom).offset(15);
        make.centerX.equalTo(self.contentView);
        make.width.equalTo(@80);
        make.height.equalTo(@36);
    }];
    
    [self.themeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.selectedDatesLabel.mas_bottom).offset(15);
        make.right.equalTo(self.contentView).offset(-16);
        make.width.equalTo(@80);
        make.height.equalTo(@36);
        make.bottom.equalTo(self.contentView).offset(-30); // 设置底部约束
    }];
}

- (void)setupInitialData {
    [self updateSelectedDatesDisplay];
}

#pragma mark - Action Methods

- (void)clearButtonTapped:(UIButton *)button {
    [self.calendarView clearSelectedDates];
    self.statusLabel.text = @"📅 请选择日期（最多10个）";
}

- (void)removeLastButtonTapped:(UIButton *)button {
    NSDate *removedDate = [self.calendarView removeLastSelectedDate];
    
    if (removedDate) {
        // 显示删除成功的提示
        NSString *dateString = [self.dateFormatter stringFromDate:removedDate];
        self.statusLabel.text = [NSString stringWithFormat:@"🗑️ 已删除日期：%@", dateString];
        
        // 震动反馈
        if (@available(iOS 10.0, *)) {
            UIImpactFeedbackGenerator *feedbackGenerator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
            [feedbackGenerator impactOccurred];
        }
        
        // 2秒后恢复状态文本
        __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if (strongSelf) {
                [strongSelf updateStatusLabel];
            }
        });
        
        NSLog(@"🗑️ 删除了最后选中的日期: %@", dateString);
    } else {
        // 没有选中的日期时的提示
        self.statusLabel.text = @"⚠️ 没有可删除的日期";
        
        // 震动反馈
        if (@available(iOS 10.0, *)) {
            UIImpactFeedbackGenerator *feedbackGenerator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
            [feedbackGenerator impactOccurred];
        }
        
        // 2秒后恢复状态文本
        __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if (strongSelf) {
                [strongSelf updateStatusLabel];
            }
        });
        
        NSLog(@"⚠️ 尝试删除日期，但没有选中的日期");
    }
}

- (void)themeButtonTapped:(UIButton *)button {
    self.currentThemeIndex = (self.currentThemeIndex + 1) % 4;
    
    KooCalendarConfig *config;
    NSString *themeName;
    
    switch (self.currentThemeIndex) {
        case 0:
            config = [KooCalendarConfig imageBasedConfig];
            themeName = @"图片设计主题";
            break;
        case 1:
            config = [KooCalendarConfig defaultConfig];
            themeName = @"默认主题";
            break;
        case 2:
            config = [KooCalendarConfig minimalistConfig];
            themeName = @"简约主题";
            break;
        case 3:
            config = [KooCalendarConfig darkThemeConfig];
            themeName = @"深色主题";
            break;
        default:
            config = [KooCalendarConfig imageBasedConfig];
            themeName = @"图片设计主题";
            break;
    }
    
    self.calendarView.config = config;
    
    // 显示主题切换提示
    self.statusLabel.text = [NSString stringWithFormat:@"🎨 已切换到%@", themeName];
    
    // 2秒后恢复原文本
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf) {
            [strongSelf updateStatusLabel];
        }
    });
}

#pragma mark - Helper Methods

- (void)updateSelectedDatesDisplay {
    NSArray *selectedDates = self.calendarView.selectedDates;
    
    if (selectedDates.count == 0) {
        self.selectedDatesLabel.text = @"当前选中的日期：无";
    } else {
        NSMutableString *datesString = [[NSMutableString alloc] initWithString:@"当前选中的日期：\n"];
        
        // 对日期进行排序
        NSArray *sortedDates = [selectedDates sortedArrayUsingComparator:^NSComparisonResult(NSDate *date1, NSDate *date2) {
            return [date1 compare:date2];
        }];
        
        for (NSInteger i = 0; i < sortedDates.count; i++) {
            NSDate *date = sortedDates[i];
            NSString *dateString = [self.dateFormatter stringFromDate:date];
            [datesString appendString:dateString];
            
            if (i < sortedDates.count - 1) {
                [datesString appendString:@"  "];
            }
        }
        
        self.selectedDatesLabel.text = datesString;
    }
}

- (void)updateStatusLabel {
    NSInteger selectedCount = self.calendarView.selectedDates.count;
    NSInteger maxCount = self.calendarView.config.maxSelectCount;
    
    if (selectedCount == 0) {
        self.statusLabel.text = [NSString stringWithFormat:@"📅 请选择日期（最多%ld个）", (long)maxCount];
    } else if (selectedCount < maxCount) {
        self.statusLabel.text = [NSString stringWithFormat:@"✅ 已选择%ld个日期（还可选择%ld个）", (long)selectedCount, (long)(maxCount - selectedCount)];
    } else {
        self.statusLabel.text = [NSString stringWithFormat:@"🚫 已达到最大选择数量（%ld个）", (long)maxCount];
    }
}

#pragma mark - KooCalendarViewDelegate

- (void)calendarView:(KooCalendarView *)calendarView 
       selectedDates:(NSArray<NSDate *> *)selectedDates
         changedDate:(NSDate *)changedDate 
          isSelected:(BOOL)isSelected {
    
    // 更新显示
    [self updateSelectedDatesDisplay];
    [self updateStatusLabel];
    
    // 打印日志
    NSString *dateString = [self.dateFormatter stringFromDate:changedDate];
    NSString *action = isSelected ? @"选中" : @"取消选中";
    NSLog(@"📅 %@了日期: %@，当前总共选中 %ld 个日期", action, dateString, (long)selectedDates.count);
}

- (void)calendarView:(KooCalendarView *)calendarView 
reachedMaxSelectCount:(NSInteger)maxCount {
    
    self.statusLabel.text = [NSString stringWithFormat:@"⚠️ 最多只能选择%ld个日期", (long)maxCount];
    
    // 震动反馈
    if (@available(iOS 10.0, *)) {
        UIImpactFeedbackGenerator *feedbackGenerator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
        [feedbackGenerator impactOccurred];
    }
    
    // 2秒后恢复状态文本
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf) {
            [strongSelf updateStatusLabel];
        }
    });
    
    NSLog(@"⚠️ 达到最大选择数量限制: %ld", (long)maxCount);
}

- (void)calendarView:(KooCalendarView *)calendarView 
    monthChangedTo:(NSDate *)currentDate {
    
    NSDateFormatter *monthFormatter = [[NSDateFormatter alloc] init];
    monthFormatter.dateFormat = @"yyyy年MM月";
    NSString *monthString = [monthFormatter stringFromDate:currentDate];
    
    NSLog(@"📆 月份切换到: %@", monthString);
}

#pragma mark - KooCalendarDataSource

- (NSString *)calendarView:(KooCalendarView *)calendarView 
        displayTextForDate:(NSDate *)date {
    
    // 为特殊日期添加自定义显示文本
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *today = [NSDate date];
    
    if ([calendar isDate:date inSameDayAsDate:today]) {
        return @"今";
    }
    
    NSDate *tomorrow = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:today options:0];
    if ([calendar isDate:date inSameDayAsDate:tomorrow]) {
        return @"明";
    }
    
    NSDate *dayAfterTomorrow = [calendar dateByAddingUnit:NSCalendarUnitDay value:2 toDate:today options:0];
    if ([calendar isDate:date inSameDayAsDate:dayAfterTomorrow]) {
        return @"后";
    }
    
    // 其他日期返回nil，使用默认显示
    return nil;
}

- (BOOL)calendarView:(KooCalendarView *)calendarView 
     shouldSelectDate:(NSDate *)date {
    
    // 只允许选择今天及以后的日期
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *today = [NSDate date];
    
    NSComparisonResult result = [calendar compareDate:date toDate:today toUnitGranularity:NSCalendarUnitDay];
    BOOL shouldSelect = (result != NSOrderedAscending);
    
    if (!shouldSelect) {
        NSLog(@"❌ 不能选择过去的日期: %@", [self.dateFormatter stringFromDate:date]);
    }
    
    return shouldSelect;
}

@end
